#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <fstream>

#include "TFile.h"
#include "TString.h"
#include "TTree.h"

#include "CommandLineInterface.hh"
#include "Peaks.hh"

using namespace std;

int main(int argc, char* argv[]){
  char* InputFile = NULL;
  char* OutputFile = NULL;
  char* HOutputFile = NULL;
  char* Name = NULL;
  CommandLineInterface* interface = new CommandLineInterface();

  interface->Add("-i", "inputfile", &InputFile);
  interface->Add("-o", "outputfile", &OutputFile);
  interface->Add("-h", "also produce histogramm output file _hist.root", &HOutputFile);

  interface->CheckFlags(argc, argv);

  if(InputFile == NULL || OutputFile == NULL ){
    cerr<<"You have to provide both the input file and the output file!"<<endl;
    exit(1);
  }
  cout<<"input file: "<<InputFile<< endl;
  if(HOutputFile == NULL){
    cerr<<"No Histogram file created."<<endl;
    exit(1);
  }
  int npeaks = 16;


  TFile* File = new TFile(InputFile);
  TIter next(File->GetListOfKeys());
  TKey *key;
  ofstream output(OutputFile);
  output << "pos\t";
  output << "name"<< endl;
  int rangemin=0;
  int rangemax=0;
  int res = 1;
  bool rej = true;
  int cddet = 1;
  int i;
  while ((key=(TKey*)next())){
    if(strcmp(key->GetClassName(),"TH1F") == 0){
      Name = (char*)key->GetName();
      if(strstr(Name,"Id")){
	cout << "Histoname " << Name << endl;
	cddet =0;
	i=0;
	char temp[10], *ptr;
	ptr = Name;       //Hilfspointer
	while(*ptr < '0' || *ptr > '9') 
	  ptr++; // Bis zur ersten Zahl
	while(*ptr >= '0' && *ptr <= '9') //Alle aneinanderh?ngenden Zahlen
	  temp[i++] = *ptr++;  // in temp speichern
	temp[i] = '\0'; //0-Terminierung 
	cddet = atoi(temp); //in int umwandeln
	if(cddet==1){
	  Find(File, Name, OutputFile, 350, 750, 16, 2, 0.001, HOutputFile, true, 0);
	  Find(File, Name, OutputFile, 1000, 1350, 16, 2, 0.001, HOutputFile, true, 1);	
	}
	else if(cddet==3){
	  Find(File, Name, OutputFile, 350, 750, 16, 2, 0.001, HOutputFile, true, 0);
	  Find(File, Name, OutputFile, 1000, 1350, 16, 2, 0.001, HOutputFile, true, 1);	
	}
	/*
	else if(cddet==1){
	  Find(File, Name, OutputFile, 400, 900, 16, 2, 0.001, HOutputFile, true, 0);
	  Find(File, Name, OutputFile, 1150, 1650, 16, 2, 0.001, HOutputFile, true, 1);	
	}
	else if(cddet==3){
	  Find(File, Name, OutputFile, 400, 900, 16, 2, 0.001, HOutputFile, true, 0);
	  Find(File, Name, OutputFile, 1200, 1700, 16, 2, 0.001, HOutputFile, true, 1);	
	}
	*/
	else
	  continue;
      }
    }
  }
  return 0;
}
